<script>

import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin'
import { getAction, postAction } from '@api/manage'
import { JVXETypes } from '@comp/jeecg/JVxeTable'
import dayjs from 'dayjs'
import JFormContainer from '@comp/jeecg/JFormContainer.vue'

export default {
  name: 'QcReportBatchForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false
    },
    reportType: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 2 }
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 18 }
      },
      model: {
        inspectionResult: 1,
        inspectionDate: dayjs().format('YYYY-MM-DD')
      },
      validatorRules: {},
      // 检验报告单
      qcReportTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '检验单号',
            key: 'reportNumber',
            type: JVXETypes.normal,
            width: '140px'
          },
          {
            title: '抽检数量',
            key: 'samplingQuantity',
            type: JVXETypes.inputNumber,
            placeholder: '请输入${title}'
          }
        ]
      },
      // 检验项目
      qcReportInspectionItemTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '检验项目',
            key: 'itemName',
            type: JVXETypes.normal,
            minWidth: '200px'
          },
          {
            title: '上限值',
            key: 'upperLimit',
              type: JVXETypes.normal,
            width:"200px",
            defaultValue:'',
          },
          {
            title: '标准值',
            key: 'qualityStandard',
            type: JVXETypes.normal,
            width: '200px'
          },
          {
            title: '下限值',
            key: 'lowerLimit',
              type: JVXETypes.normal,
            width:"200px",
            defaultValue:'',
          },
          {
            title: '结果录入',
            key: 'result',
            type: JVXETypes.inputNumber,
            placeholder: '请输入${title}',
            defaultValue: '',
            width:"200px",
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '备注',
            key: 'remark',
            type: JVXETypes.normal,
            minWidth:"200px",
            defaultValue:'',
          },
        ]
      },
      url: {
        editBatch: '/qms/inspection/report/editBatch',
        rawMaterialInspectionStandardItem: {
          list: '/qc/eneQcMaterialsCheck/queryEneQcMaterialsCheckDetailByMainId'
        },
        packagingMaterialInspectionStandardItem: {
          list: '/packagecheck/enePackageCheck/queryEnePackageCheckDetailByMainId'
        },
        finishedProductFinalInspectionStandardItem: {
          list: '/eneinspectioncheck/eneInspectionCheck/queryEneInspectionCheckDetailByMainId'
        },
        commonCheckStandardItem: {
          list: '/commoncheck/eneCommonCheck/queryEneCommonCheckDetailByMainId'
        }
      },
      standardMap: {}, // 存储ID到名称的映射
    }
  },
  mounted() {
    this.loadStandardOptions();
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
    inspectionStandardCode() {
      if (this.reportType === 'raw-material') {
        return 'ene_qc_materials_check,check_standard,id'
      } else if (this.reportType === 'packaging-material') {
        return 'ene_package_check,check_standard,id'
      } else if (this.reportType === 'finished-product-final') {
        return 'ene_inspection_check,check_standard,id'
      } else if (this.reportType === 'hardware') {
        return 'ene_common_check,check_standard,id'
      }
      return ''
    },
    inspectionStandardItemUrl() {
      if (this.reportType === 'raw-material') {
        return this.url.rawMaterialInspectionStandardItem.list
      } else if (this.reportType === 'packaging-material') {
        return this.url.packagingMaterialInspectionStandardItem.list
      } else if (this.reportType === 'finished-product-final') {
        return this.url.finishedProductFinalInspectionStandardItem.list
      } else if (this.reportType === 'hardware') {
        return this.url.commonCheckStandardItem.list
      }
      return ''
    }
  },
  methods: {
    // 加载检验标准选项
    async loadStandardOptions() {
      try {
        if (this.reportType === 'raw-material') {
        // 获取下拉选项数据
        const res = await getAction('/sys/dict/getDictItems/ene_qc_materials_check,check_standard,id');
        if (res.success) {
          // 建立ID到名称的映射
          this.standardMap = res.result.reduce((map, item) => {
            map[item.value] = item.text;
            return map;
          }, {});
        }
      }
      } catch (e) {
        console.error('加载检验标准失败', e);
      }
    },
    edit(records) {
      this.qcReportTable.dataSource = records
      this.qcReportInspectionItemTable.dataSource = []
    },
    async handleSubmit() {
      const validate = await this.$refs.form.validate()
      if (!validate) {
        return
      }
      const errMap = await this.$refs.qcReportInspectionItem.validateTable()
      if (errMap) {
        return
      }
      const formDataList = this.qcReportTable.dataSource.map(item => {
        return {
          id: item.id,
          standardId: this.model.standardId,
          samplingQuantity: item.samplingQuantity,
          inspectionResult: this.model.inspectionResult,
          inspectionDate: this.model.inspectionDate,
          remark: this.model.remark,
          qcReportInspectionItemList: this.qcReportInspectionItemTable.dataSource.map(item => {
            return {
              ...item,
              id: null
            }
          })
        }
      })
      this.request(formDataList)
    },
    request(formData) {
      this.confirmLoading = true
      postAction(this.url.editBatch, formData)
        .then((res) => {
          if (res.success) {
            this.$message.success('保存成功')
            this.$emit('ok')
            this.close()
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    handleInspectionStandardChange(value) {
      const params = { id: value }
      getAction(this.inspectionStandardItemUrl, params).then(res => {
        let { result } = res
        if (result) {
          this.qcReportInspectionItemTable.dataSource = result.map(item => {
            return {
              inspectionStandardId: item.pid || item.packageId || item.inspectionId || item.commonId,
              itemName: item.analyseItem,
              qualityStandard: item.qualityIndex,
              upperLimit: item.upperLimit,
              lowerLimit: item.lowerLimit,
              remark: item.remark,
              result: '',
            };
          });
        }
      })
    },
    // 自动计算方法
    calculateAutoValues() {
      if (!this.model.standardId || this.reportType !== 'raw-material') return;
      // 获取标准名称
      const standardName = this.standardMap[this.model.standardId] || '';
      const dataSource = this.qcReportInspectionItemTable.dataSource;
      const findValue = (keyword) => {
        const item = dataSource.find(i => i.itemName.includes(keyword));
        return item && item.result !== '' ? parseFloat(item.result) : null;
      };
      // 无水硫酸钠计算逻辑
      if (standardName.includes("无水硫酸钠")) {
        // X1计算：钙镁含量
        const v_calcium = findValue('V（钙镁）');
        const c_calcium = findValue('C（钙镁）');
        const w_calcium = findValue('W：试样的质量g');
        
        if (v_calcium !== null && c_calcium !== null && w_calcium !== null && w_calcium !== 0) {
          const x1 = (48.6 * v_calcium * c_calcium) / w_calcium;
          this.setItemValue('X1：钙镁含量%（以Mg计）', x1.toFixed(4));
        }
        
        // X2计算：氯化物含量
        const v_chloride = findValue('V（氯化物）');
        const v0_chloride = findValue('V0（氯化物）');
        const c_chloride = findValue('C（氯化物）');
        
        if (v_chloride !== null && v0_chloride !== null && c_chloride !== null && w_calcium !== null && w_calcium !== 0) {
          const x2 = (70.9 * (v_chloride - v0_chloride) * c_chloride) / w_calcium;
          this.setItemValue('X2：氯化物的含量%(以NaCL%计)', x2.toFixed(4));
        }
        
        // 硫酸钠含量计算
        const x1_val = findValue('X1：钙镁含量%（以Mg计）');
        const x2_val = findValue('X2：氯化物的含量%(以NaCL%计)');
        const x3 = findValue('X3：水分含量%');
        const x4 = findValue('X4：水不溶物%');
        
        if (x1_val !== null && x2_val !== null && x3 !== null && x4 !== null) {
          const sulfate = 100 - (4.951 * x1_val + 1.648 * x2_val + x3 + x4);
          this.setItemValue('硫酸钠含量x%', sulfate.toFixed(4));
        }
      }
      
      // 纯碱计算逻辑
      else if (standardName.includes("纯碱")) {
        // 碳酸钠含量计算
        const c_carbonate = findValue('C（碳酸钠）');
        const v_carbonate = findValue('V（碳酸钠）');
        const v0_carbonate = findValue('V0（碳酸钠）');
        const w_carbonate = findValue('W：试样的质量g');
        
        if (c_carbonate !== null && v_carbonate !== null && v0_carbonate !== null && w_carbonate !== null && w_carbonate !== 0) {
          const carbonate = (c_carbonate * (v_carbonate - v0_carbonate) * 0.053) / w_carbonate;
          this.setItemValue('碳酸钠含量x%', carbonate.toFixed(4));
        }
        
        // 灼烧失量计算
        const w_burn = findValue('W：试样的质量g');
        const w1_burn = findValue('W1：样品烘干后质量');
        
        if (w_burn !== null && w1_burn !== null && w_burn !== 0) {
          const burnLoss = ((w_burn - w1_burn) / w_burn);
          this.setItemValue('X：灼烧失量的质量分数%', burnLoss.toFixed(4));
        }
        
        // 氰化物含量计算
        const v_cyanide = findValue('V（氰化物）');
        const v0_cyanide = findValue('V0（氰化物）');
        const c_cyanide = findValue('C（氰化物）');
        const w_cyanide = findValue('W：试样的质量g');
        const x_cyanide = findValue('X：灼烧失量的质量分数%');
        
        if (v_cyanide !== null && v0_cyanide !== null && c_cyanide !== null && 
            w_cyanide !== null && x_cyanide !== null && w_cyanide !== 0) {
          const cyanide = (10 * (v_cyanide - v0_cyanide) * c_cyanide * 58.44) / 
                         (w_cyanide * (100 - x_cyanide));
          this.setItemValue('氰化物含量x%', cyanide.toFixed(4));
        }
      }
      
      // 液碱计算逻辑
      else if (standardName.includes("液碱")) {
        const v_alkali = findValue('V：滴定样品耗用的盐酸标准溶液的体积mL');
        const c_alkali = findValue('C：盐酸标准溶液的浓度moL/L');
        const w_alkali = findValue('W：试样的质量g');
        if (v_alkali !== null && c_alkali !== null && w_alkali !== null && w_alkali !== 0) {
          const alkali = (v_alkali * c_alkali * 0.04 * 20) / w_alkali;
          this.setItemValue('氢氧化钠百分含量x%', alkali.toFixed(4));
        }
      }
    },
    
    // 设置项目值
    setItemValue(itemName, value) {
      const index = this.qcReportInspectionItemTable.dataSource.findIndex(
        item => item.itemName.includes(itemName)
      );
      if (index !== -1) {
        this.$set(this.qcReportInspectionItemTable.dataSource[index], 'result', value);
      }
    },
    handleDelete({ deleteRows }) {
      this.qcReportInspectionItemTable.dataSource = this.qcReportInspectionItemTable.dataSource.filter(row =>
        !deleteRows.some(item => item.id === row.id)
      )
    }
  }
}
</script>

<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <j-vxe-table
              style="margin: 9px 0"
              keep-source
              ref="qcReport"
              :loading="qcReportTable.loading"
              :columns="qcReportTable.columns"
              :dataSource="qcReportTable.dataSource"
              :maxHeight="300"
              :disabled="formDisabled"
              :rowNumber="true"
              :rowSelection="false"
              :toolbar="false"
            />
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="检验标准" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="samplingQuantity">
              <j-search-select-tag
                placeholder="请选择检验标准"
                @change="handleInspectionStandardChange"
                v-model="model.standardId"
                :dict="inspectionStandardCode" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="检验日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="inspectionDate">
              <j-date placeholder="请选择检验日期" v-model="model.inspectionDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <j-vxe-table
              keep-source
              ref="qcReportInspectionItem"
              :loading="qcReportInspectionItemTable.loading"
              :columns="qcReportInspectionItemTable.columns"
              :dataSource="qcReportInspectionItemTable.dataSource"
              :maxHeight="300"
              :disabled="formDisabled"
              :rowNumber="true"
              :rowSelection="true"
              :toolbar="true"
              :toolbarConfig="{
                slots: ['prefix', 'suffix'],
                btn: ['remove', 'clearSelection'],
              }"
              @remove="handleDelete"
              @valueChange="calculateAutoValues()"
            >
            </j-vxe-table>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="检验结果" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="inspectionResult">
              <j-dict-select-tag type="radio" v-model="model.inspectionResult" dictCode="qc_inspection_result" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="备注" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="remark">
              <a-input v-model="model.remark" placeholder="请输入备注" :disabled="formDisabled" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<style scoped>

</style>